<?php


namespace Api\Http\Controllers;


use AllowDynamicProperties;
use Api\Service\FilmService;
use Api\traits\ApiResponse;
use Carbon\Carbon;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Image;
use Intervention\Image\ImageManager;
use Modules\Cms\Models\Resource;
use EasyWeChat\MiniApp\Application;
use Modules\Member\Models\Members;
use Modules\Member\Models\MembersDelete;
use Modules\Member\Models\MembersProfit;
use Modules\Member\Models\MembersShareImage;
use Modules\Member\Models\MembersWithdraw;
use Modules\Order\Models\LevelOrders;
use Modules\Order\Models\Orders;
use Modules\Shop\Models\Coupon;
use Modules\Shop\Models\Pivots\UserHasCoupons;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;


/**
 * @group 用户模块
 *
 * @subgroup 用户管理
 * @subgroupDescription CatchAdmin 后台用户管理
 *
 */
#[AllowDynamicProperties] class MemberController extends Controller
{
    use ApiResponse;

    private $qrCodeGenerator;

    public function __construct(
        protected readonly Members        $members,
        protected readonly UserHasCoupons $membersCoupon
    )
    {
        $this->accessKeySecret = env("ACCESSKEY");

        $this->accessKeyId = env("ACCESSSECRET");;

        $this->endpoint = env("ENDPOINT");


        $this->bucket = env("BUCKET");
    }

    /**
     * 新增用户
     *
     * @bodyParam Membername string required 用户名
     * @bodyParam password string required 密码
     * @bodyParam email string 邮箱
     * @bodyParam mobile string 手机号
     * @bodyParam department_id int 部门
     * @bodyParam roles integer[] 角色
     * @bodyParam jobs integer[] 职位
     *
     * @responseField data int 新增ID
     *
     * @return false|mixed
     * @throws InvalidArgumentException
     */
    public function store(Request $request)
    {

        if (!empty($request->post('code'))) {
            $code = $request->input('code', '');
            $config = [
                'app_id' => env('APPID'),
                'secret' => env('SECRET'),
            ];
            $app = new Application($config);
            $utils = $app->getUtils();
            $result = $utils->codeToSession($code);
//            $result = ['openid'=>'oZ-so7ZGj4ar0TVtDzqDfuO65y21312','unionid'=>'oBf7e6fijUiMuz8Gv9lK9zJ99G5A'];
            $memberInfo = Members::where('open_id', $result['openid'])->select(['open_id', 'token', 'union_id', 'updated_at', 'created_at', 'id', 'mobile','longitude','latitude'])->first();
            if (!empty($memberInfo)){
                if (empty($memberInfo->token)) {
                    $memberInfo->token = sha1(md5(uniqid()));
                    $memberInfo->save();
                }
                $memberInfo->is_first_login = 0;
            }else{
                $flag = 0;
                for ($i = 0; $i < 10; $i++) {
                    $charid = strtoupper(md5(uniqid(rand(), true)));
                    $random = substr($charid, 0, 6);
                    $info = Members::where('invite_code', $random)->first();
                    if (empty($info)) {
                        $flag = 1;
                        break;
                    }
                }
                if ($flag == 0) {
                    return $this->fail('请重新扫码注册');
                }
                $data['open_id'] = $result['openid'];
                $data['invite_code'] = $random;
                $data['avatar'] = 'https://xingjukuaidi.oss-cn-beijing.aliyuncs.com/image/avatar.png';
                $token = sha1(md5(uniqid()));
                $data['token'] = $token;
                $data['union_id'] = $result['unionid'];
                $data['longitude'] = $result['longitude'] ?? 0;
                $data['latitude'] = $result['latitude'] ?? 0;
                if (!empty($request->input('invite_code'))) {
                    $pinfo = Members::where('invite_code', $request->input('invite_code'))->first();
                    $data['pid'] = $pinfo->id;
                    $pathInfo = Redis::hget($data['pid'], 'path');
                }
                $data['created_at'] = time();
                $memberInfo = $this->members::create($data);

                $couponInfo = Coupon::where('type', 1)->where('status', 1)->orderBy('id', 'desc')->first();
                if (!empty($couponInfo)) { //添加注册优惠券
                    $this->membersCoupon->user_id = $memberInfo->id;
                    $this->membersCoupon->coupon_id = $couponInfo->id;
                    $this->membersCoupon->save();
                }
                //添加上级路径
                if (!empty($pinfo)) {
                    if ($pinfo->pid == 0) {
                        $path = $pinfo->id;
                    } else {
                        if (!isset($pathInfo)) {
                            $path = $pinfo->id;
                        } else {
                            $path = $pathInfo . "," . $pinfo->id;
                        }
                    }
                    Redis::hset($memberInfo->id, 'path', $path);
                    //为所有上级增加下级用户
                    $pathArr = explode(",", $path);
                    foreach ($pathArr as $v) {
                        $gzhOpenId = Members::where('id',$v)->value('gzh_open_id');
                        if(!empty($gzhOpenId)){
                            $data = [
                                'thing1'=>['value'=> '微信用户'],
                                'time2' =>['value' => date("Y-m-d H:i:s",time())]
                            ];
                            $wechat = new WechatController();
                            $wechat->sendOfficialMessage($gzhOpenId,'G4KdHWHQtFpPTf1o3UrLrq6kkGWpvEpYV6gtAHSH3nc',$data);
                        }
                        //获取上级团队信息
                        $teamCache = Redis::hget($v, "team");
                        if (empty($teamCache)) {
                            Redis::hset($v, 'team', $memberInfo->id);
                        }elseif(!in_array($memberInfo->id, $pathArr)) {
                            $teamCache .= "," . $memberInfo->id;
                            Redis::hset($v, 'team', $teamCache);
                        }
                    }
                }
                $memberInfo->is_first_login = 1;
                $memberInfo->reduce_price = $couponInfo->reduce_price;
            }
            if ($memberInfo) {
                return $this->data($memberInfo->toArray());
            } else {
                return $this->fail('登录失败');
            }
        } else {
            return $this->fail('code码无效');
        }
    }

    public function publishInfo()
    {
        if ($this->getLoginUser()->pid != 0) {
            $pinfo = Members::find($this->getLoginUser()->pid);
            $data['recommend_name'] = $pinfo->username;
            $data['mobile'] = $pinfo->mobile;
        } else {
            $data['recommend_name'] = '';
            $data['mobile'] = '';
        }
        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];
        $team = Redis::hget($this->getLoginUserId(), 'team');
        $publishCount = 0;  //总推广人数
        $publishOrderCount = 0;  //总推广订单
        $todayOrderCount = 0;  //总推广订单
        $friendCount = Members::where('pid', $this->getLoginUserId())->count(); //直推人数
        if (!empty($team)) {
            $arr = explode(",", $team);
            $publishCount = count($arr);  //推广总人数
            $arr[] = $this->getLoginUserId();
            $publishOrderCount = Orders::whereIn('user_id', function ($query) use ($arr) {
                $query->from('members')->whereIn('id', $arr)->select(['id'])->get();
            })->whereIn('type_code', [1, 2, 3])->count();  //推广总订单
            $todayOrderCount = Orders::whereIn('user_id', function ($query) use ($arr) {
                $query->from('members')->whereIn('id', $arr)->select(['id'])->get();
            })->whereNotNull('paid_at')->whereIn('type_code', [1, 2, 3])->whereBetween('created_at', $today)->count(); //今日订单
        }
        $data['publish_count'] = $publishCount;
        $data['friend_count'] = $friendCount;
        $data['publish_order_count'] = $publishOrderCount;
        $data['today_order_count'] = $todayOrderCount;
        $data['profit'] = MembersProfit::whereBetween('created_at', $today)->whereIn('type',[1,4])
            ->where('user_id', $this->getLoginUserId())->where('status', '<>', 2)->sum('profit'); //首重佣金和续重佣金
        return $this->data($data);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * 用户推广
     */
    public function publishList(Request $request)
    {
        $search = $request->get('search');
        $limit = $request->get('limit', 10);
        $data = [];

        $team = Redis::hget($this->getLoginUserId(), 'team');
        $publishCountOrder = 0;  //总推广订单
        $friendCount = Members::where('pid', $this->getLoginUserId())->count(); //直推人数
        $type = $request->get('type', '');
        $where = [];
        if ($type == 1) {
            $where[] = ['pid', '=', $this->getLoginUserId()];
        } elseif ($type == 2) {
            $where[] = ['pid', '<>', $this->getLoginUserId()];
        }
        if (!empty($team)) {
            $arr = explode(",", $team);
            if(!empty($search) &&!in_array($search, $arr)){
                return  $this->fail('该成团不是您的团队无法查询');
            }
            if (!empty($search) && in_array($search, $arr)) {
                $list = Members::where('id', $search)->where($where)->orderBy('id', 'desc')->select(['id', 'pid', 'username', 'user_level', 'created_at', 'avatar'])->paginate($limit)->toArray();
            } else {
                $list = Members::whereIn('id', $arr)->where($where)->orderBy('id', 'desc')->select(['id', 'pid', 'username', 'user_level', 'created_at', 'avatar'])->paginate($limit)->toArray();
            }
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['order_count'] = Orders::where('user_id', $v['id'])->whereIn('type_code', [1, 2, 3])->count();
                $teamPublishCache = Redis::hget($v['id'], 'team');
                if (empty($teamPublishCache)) {
                    $publishCount = 0;
                } else {
                    $publishArr = explode(",", $teamPublishCache);
                    $publishCount = count($publishArr);
                }
                $list['data'][$k]['publish_count'] = $publishCount;
                $list['data'][$k]['profit'] = '';
            }
            $data['list'] = $list;
        } else {
            $data['list'] = [];
        }

        return $this->data($data);

    }

    public function bindMobile(Request $request)
    {

        $code = $request->post('code');
        $config = [
            'app_id' => env('APPID'),
            'secret' => env('SECRET'),
            'use_stable_access_token' => true,
        ];
        $app = new Application($config);
        $data = [
            'code' => (string)$code,
        ];
        $json = $app->getClient()->postJson('wxa/business/getuserphonenumber', $data);
        $result = json_decode($json->getContent(), true);
        if ($result['errcode'] != 0) {
            return $this->fail($result['errmsg']);
        }
        $phoneInfo = $result['phone_info'];
        $mobile = $phoneInfo['phoneNumber'];
        Members::where('id', $this->getLoginUserId())->update(['mobile' => $mobile]);
        return $this->success('绑定成功');
    }


    /**
     * 查询用户
     *
     * @responseField id int 用户ID
     * @responseField Membername string 用户名
     * @responseField avatar string 头像
     * @responseField email string 邮箱
     * @responseField mobile string 手机号
     * @responseField department_id int 部门ID
     * @responseField roles integer[] 角色
     * @responseField jobs integer[] 职位
     * @responseField permissions integer[] 权限
     * @responseField created_at string 创建时间
     *
     * @param $id
     * @return mixed
     */
    public function show(): mixed
    {
        $userId = $this->getLoginUserId();
        $level = config('level');
        if (empty($userId)) {
            return $this->fail('token无效');
        }
        $memberInfo = $this->members::find($this->getLoginUserId())->toArray();
        $memberInfo['city_agent_show'] = 0;
        $time = time();
        if($memberInfo['city_agent_status'] == 1 && $memberInfo['agent_end_at']<time()){
            $memberInfo2 = $this->members::find($this->getLoginUserId());
            $memberInfo2->city_agent_status = 0;
            $memberInfo['city_agent_status'] = 0;
            $memberInfo2->city_agent_name = '';
            $memberInfo2->save();
        }
        if ($memberInfo['pid'] != 0) {
            $pinfo = $this->members::select(['username', 'real_name', 'mobile','wechat'])->find($memberInfo['pid']);
            if(empty($pinfo)){
                $memberInfo['pinfo'] = [];
                $memberInfo['pinfo_wechat'] = '';
            }else{
                $memberInfo['pinfo'] = $pinfo;
                $memberInfo['pinfo_wechat'] = $pinfo->wechat;
            }

        } else {
            $memberInfo['pinfo'] = [];
            $memberInfo['pinfo_wechat'] = '';
        }
        $teamCache = Redis::hget($this->getLoginUserId(), 'team');
        $memberInfo['disable_price'] = MembersProfit::where('user_id', $userId)->where('status', 0)->sum('profit');  //待入账
        if(!empty($teamCache)){
            $teamArr = explode(",", $teamCache);
            $startMonth = Carbon::now()->startOfMonth()->timestamp;
            $endMonth = Carbon::now()->endOfMonth()->endOfDay()->timestamp;
            $orderCount = Orders::whereIn('user_id', function ($query) use ($teamArr) {
                return $query->from('members')->whereIn('id', $teamArr)->select(['id'])->get();
            })->where('type_code',3)->whereBetween('created_at', [$startMonth, $endMonth])->count();
            if($orderCount>=$level['order_count'] && $memberInfo['city_agent_status']  !=1){
                $memberInfo['city_agent_show'] = 1;
            }
        }
        $memberInfo['agent_start_at'] = $memberInfo['agent_start_at'] ? date('Y-m-d H:i:s', $memberInfo['agent_start_at']) : '';
        $memberInfo['agent_end_at'] = $memberInfo['agent_end_at'] ? date('Y-m-d H:i:s', $memberInfo['agent_end_at']) : '';
        return $this->data($memberInfo);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * 升级市区代理
     */
    public function updateCityAgent(Request $request)
    {
        $userId = $this->getLoginUserId();
        $level = config('level');
        $cityName = $request->post('city_name');
        $now = Carbon::now()->timestamp;
        $cityAgent = Members::where('agent_city_name', 'like', $cityName."%")->where('agent_end_at','>',$now)->where('status',1)->first();
        if(!empty($cityAgent)){
            return  $this->fail('该区域已有代理,请选择其他区域');
        }
        $teamCache = Redis::hget($this->getLoginUserId(), 'team');
        $teamArr = explode(",", $teamCache);
        $teamArr[] = $userId;
        $startMonth = Carbon::now()->startOfMonth()->timestamp;
        $endMonth = Carbon::now()->endOfMonth()->endOfDay()->timestamp;
        $orderCount = Orders::whereIn('user_id', function ($query) use ($teamArr) {
            return $query->from('members')->whereIn('id', $teamArr)->select(['id'])->get();
        })->where('type_code',3)->whereBetween('updated_at', [$startMonth, $endMonth])->count();
        if($orderCount >=$level['order_count']){
            //清空其他该城市代理
            $this->members->whereLike('agent_city_name',$cityName.'%')->update(['agent_city_name'=>null]);
            $memberInfo = $this->members::find($userId);
            $memberInfo->city_agent_status = 1;
            $startNextMonet = strtotime(date('Y-m-01', strtotime('+1 month')));
            $endTime = $startNextMonet + 365*86400;
            $memberInfo->agent_start_at = $startNextMonet;
            $memberInfo->agent_end_at = $endTime;
            $memberInfo->agent_city_name = $cityName;
            $memberInfo->save();
            return $this->success('升级代理成功');
        }else{
            return $this->fail('不满足代理升级条件');
        }

    }

    public function cityAgentInfo()
    {
        $userId = $this->getLoginUserId();
        $memberInfo = $this->members::find($userId)->toArray();
        $now = Carbon::now()->timestamp;
        $level = config('level');
        if(empty($memberInfo['agent_end_at']) || $memberInfo['agent_end_at'] < $now){
            $month = [
                Carbon::now()->startOfMonth()->copy()->startOfDay(),
                Carbon::now()->timestamp,
            ];
            $ids = Redis::hget($userId,'team');
            if(!empty($ids)){
                $ids = explode(",", $ids);
            }else{
                $ids = [];
            }
            $ids[] = $userId;
            $orderCount = Orders::whereIn('user_id',function ($query)use ($ids){
               return $query->from('members')->whereIn('id', $ids)->select(['id'])->get();
            })->whereBetween('created_at',$month)->where('type_code',3)->count();
            $memberInfo['today_count'] = '0';
            $memberInfo['week_count'] = '0';
            $memberInfo['month_count'] = $orderCount;
            $memberInfo['agent_start_at'] =  '';
            $memberInfo['agent_end_at'] = '';
            $memberInfo['order_count'] = $level['order_count'] ?? '1500';
            return $this->data($memberInfo);
        }
        $today = [
            Carbon::now()->startOfDay()->timestamp,
            Carbon::now()->endOfDay()->timestamp
        ];
        $week = [
            Carbon::now()->startOfWeek()->timestamp,
            Carbon::now()->timestamp,
        ];

        $month = [
            Carbon::now()->startOfMonth()->copy()->startOfDay(),
            Carbon::now()->timestamp,
        ];
        $todayCount = Orders::whereBetween('created_at', $today)->where('created_at', '>', $memberInfo['agent_start_at'])->whereLike('sender_city',$memberInfo['agent_city_name'])->whereNotIn('type_code',[4,5,99])->count();

        $monthCount = Orders::whereBetween('created_at', $month)->where('created_at', '>', $memberInfo['agent_start_at'])->whereLike('sender_city',$memberInfo['agent_city_name'])->whereNotIn('type_code',[4,5,99])->count();
        $memberInfo['today_count'] = $todayCount;
        $memberInfo['today_profit'] = bcmul($todayCount,'0.1',2);
        $memberInfo['month_count'] = $monthCount;
        $memberInfo['month_profit'] = bcmul($monthCount,'0.1',2);
        $memberInfo['agent_start_at'] = date('Y-m-d H:i:s', $memberInfo['agent_start_at']) ?? '';
        $memberInfo['agent_end_at'] = date('Y-m-d H:i:s', $memberInfo['agent_end_at']) ?? '';

        return $this->data($memberInfo);
    }

    /**
     * 更新用户
     *
     * @urlParam id int required 用户ID
     *
     * @bodyParam Membername string required 用户名
     * @bodyParam password string 密码
     * @bodyParam email string 邮箱
     * @bodyParam mobile string 手机号
     * @bodyParam department_id int 部门
     * @bodyParam roles integer[] 角色
     * @bodyParam jobs integer[] 职位
     *
     * @responseField data bool 是否更新成功
     *
     * @param $id
     * @param OrderRequest $request
     * @return mixed
     */
    public function update($id, Request $request): mixed
    {
        $memberInfo = $this->members->where('id', $id)->first();
        if ($memberInfo->status == 2) {
            $memberInfo->token = '';
            $memberInfo->save();
            return $this->fail('账号已被封禁,请联系管理员');
        }
        $this->members->where('id', $id)->update($request->post());
        return $this->success('保存成功');
    }

    /**
     * 删除用户
     *
     * @responseField data bool 是否更新成功
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return $this->fail('注销联系客服');
//        $team = Redis::hget($id,'team');
//        if(!empty($team)){
//            $deleteLog = new MembersDelete();
//            $deleteLog->user_id = $id;
//            $deleteLog->team = $team;
//            $deleteLog->save();
//
//            $teamArr = explode(",",$team);
//            foreach ($teamArr as $v){
//                $memberInfo = $this->members->find($v);
//                $memberInfo->pid = 0;
//                $memberInfo->save();
//                Redis::hdel($v,'path');
//            }
//
//        }
//        $path = Redis::hget($id,'path');
//        if(!empty($path)){
//            $pathArr = explode(",",$path);
//            foreach ($pathArr as $v){
//                $pathTeam = Redis::hget($v,'team'); //每个上级的下级团队
//                $pathTeam = explode(",",$pathTeam);
//                $temp = [];
//                foreach ($pathTeam as $item) {
//                    if($item != $id){
//                        $temp[] = $item;
//                    } else{
//                        break;
//                    }
//                }
//                Redis::hset($v,'team',implode(",",$temp));
//            }
//        }
//        Redis::del($id);
//        $result = $this->members->deletesBy($id, true);
//        if ($result == 1) {
//            return $this->success('注销成功');
//        } else {
//            return $this->fail('注销失败');
//        }

    }

    /**
     * @return void
     * 用户二维码
     */
    public function shareImage(Request $request)
    {
        $inviteCode = $request->input('invite_code', '');
        $path = $request->input('path', '');
        $explode = explode('=', $path);
        $inviteCode = $explode[1];
        $result = MembersShareImage::where('code', $inviteCode)->first();
        if (empty($result)) {
            $appid = env('APPID');
            $secret = env('SECRET');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $client = new Client();
            $response = $client->request('GET', $url, [
            ]);
            $result2 = json_decode($response->getBody()->getContents(), true);
            $access_token = $result2['access_token'];
            if (!empty($access_token)) {
                $qrcode_url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token;
                $data = array(
                    'path' => $path, // 小程序页面路径
                    'width' => 430, // 二维码宽度
                );
                $data = json_encode($data);
                $image = file_get_contents($qrcode_url, false, stream_context_create(array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => 'Content-type: application/json',
                        'content' => $data,
                    ),
                )));

                $create['code'] = $inviteCode;
                $create['image'] = $image;
                MembersShareImage::create($create);
            }
        } else {
            $image = $result['image'];
        }
        echo $image;
    }

    //提现
    public function dowith(Request $request)
    {
        $alipay = new AlipayController();
        $userId = $this->getLoginUserId();
        $withdraw = $request->input('money', 0);
        if ($withdraw < 1 || empty($withdraw || !is_numeric($withdraw))) {
            return $this->fail('提现金额不能小于1');
        }
        $userMoney = Members::where('id', $userId)->value('price');
        if ($withdraw > $userMoney) {
            return $this->fail('余额不足');
        }
        $userInfo = Members::find($userId);
        if (empty($userInfo->withdraw_account)) {
            return $this->fail('请填写提现账号');
        }
        //增加提现记录
        $arr = [];
        $arr['user_id'] = $userId;
        $arr['money'] = $withdraw;
        $arr['account'] = $userInfo->withdraw_account;
        $arr['real_name'] = $this->getLoginUser()->real_name;
        $record = MembersWithdraw::create($arr);
        Members::where('id', $userId)->decrement('price', $withdraw);
        $paymentResult = $alipay->transferToUser($arr['account'], $withdraw, $arr['real_name']);
        if (isset($paymentResult['status']) && $paymentResult['status'] == 'SUCCESS') {
            $record->status = '1';
            $record->out_biz_no = $paymentResult['outBizNo'];
            $record->save();
            Members::where('id', $userId)->increment('withdraw_all', $withdraw);
            return $this->success('打款成功');
        } else {
            $record->status = '2';
            $return = json_decode($paymentResult, true);
            $record->fail_reason = $return['message'];
            $record->save();
            Members::where('id', $userId)->increment('price', $withdraw);
            return $this->fail('打款失败,' . $return['message']);
        }

    }

    //提现记录
    public function withdrawRecord(Request $request)
    {
        $status = $request->post('status');
        $limit = $request->get('limit', 10);
        // 当天开始时间戳
        $startOfDay = Carbon::today()->startOfDay()->timestamp;

// 当天结束时间戳
        $endOfDay = Carbon::today()->endOfDay()->timestamp;
        $where = [];
        $where[] = ['user_id', '=', $this->getLoginUserId()];
        if (!empty($status)) {
            $status -= 1;
            $where[] = ['status', '=', $status];
        }
        if (!empty($request->post('start_time')) && !empty($request->post('end_time'))) {
            $every = [
                strtotime($request->post('start_time') . "00:00:00"),
                strtotime($request->post('end_time') . "23:59:59")
            ];
        }


        $query = MembersWithdraw::where($where);
        if (!empty($request->post('start_time')) && !empty($request->post('end_time'))) {
            $query->whereBetween('created_at', $every);
        }
        $list = $query->orderByDesc('id')->paginate($limit)->toArray();
        return $this->data($list);
    }

    /**
     * @return \Illuminate\Http\Response
     * 等级中心
     */
    public function vipCenter()
    {
        $userId = $this->getLoginUserId();
        $userInfo = Members::where('id', $userId)->select(['user_level', 'user_count', 'v1_count'])->first();
        $config = config('level');
        $userInfo->v1_max = config('level')['v1_count'];
        $userInfo->v2_max = config('level')['v2_count'];
        return $this->data($userInfo->toArray());
    }

    /**
     * @return \Illuminate\Http\Response
     * 常见问题
     */
    public function cmsResource(Request $request)
    {
        $type = $request->input('type');
        $list = Resource::where('type', $type)->where('is_visible', 1)->select(['id', 'is_visible', 'name', 'content', 'url', 'description', 'type'])->orderBy('id', 'desc')->get();
        return $this->data($list->toArray());
    }

    public function getPoster()
    {
        $inviteCode = $this->getLoginUser()->invite_code;

        //获取二维码图片
        $path = 'pages/index/index?invite_code=' . $inviteCode;
        $result = MembersShareImage::where('code', $inviteCode)->first();
        if (empty($result)) {
            $appid = env('APPID');
            $secret = env('SECRET');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $client = new Client();
            $response = $client->request('GET', $url, [
            ]);
            $result2 = json_decode($response->getBody()->getContents(), true);
            $access_token = $result2['access_token'];
            if (!empty($access_token)) {
                $qrcode_url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $access_token;
                $data = array(
                    'path' => $path, // 小程序页面路径
                    'width' => 230, // 二维码宽度
                );
                $data = json_encode($data);
                $image = file_get_contents($qrcode_url, false, stream_context_create(array(
                    'http' => array(
                        'method' => 'POST',
                        'header' => 'Content-type: application/json',
                        'content' => $data,
                    ),
                )));

                $create['code'] = $inviteCode;
                $create['image'] = $image;
                MembersShareImage::create($create);
            }
        } else {
            $image = $result['image'];
        }

        $blob = $image;
        $qrCodePath = public_path($inviteCode . '.jpg');
        file_put_contents($qrCodePath, $blob);
        // 生成二维码图片
        $background = Resource::where('id', request()->get('id'))->value('url');
        $temp = explode('.', $background);
        $ext = isset($temp[4]) ? $temp[4] : 'jpg';
        if ($ext == 'jpg' || $ext == 'jpeg') {
            $baseImage = imagecreatefromjpeg($background); // 底图路径
        } else {
            $baseImage = imagecreatefrompng($background); // 底图路径
        }

        $overlayImage = imagecreatefromjpeg($qrCodePath); // 要放置的图片路径

        // 获取底图的宽度和高度
        $baseWidth = imagesx($baseImage);
        $baseHeight = imagesy($baseImage);

        // 设置覆盖图片的位置，这里是放在底图的上方，距离底图底部50像素的位置
        $x = 241; // 水平位置
        $y = 962; // 垂直位置

// 重新采样并复制覆盖图片到指定位置
        imagecopyresampled($baseImage, $overlayImage, $x, $y, 0, 0, 230, 230, imagesx($overlayImage), imagesy($overlayImage));

// 海报保存
        $filename = uniqid() . ".jpg";

        $outputPath = public_path($filename);
        imagejpeg($baseImage, $outputPath);
        unlink($qrCodePath);

// 工作完毕
        imagedestroy($baseImage);
        imagedestroy($overlayImage);
        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        $provider = new StaticCredentialsProvider($accessKeyId, $accessKeySecret);
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        $endpoint = $this->endpoint;
// 填写Bucket名称，例如example bucket。
        $bucket = $this->bucket;
// 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。

// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        $filePath = $outputPath;

        try {
            $config = array(
                "provider" => $provider,
                "endpoint" => $endpoint,
            );
            $ossClient = new OssClient($config);
            $filename2 = 'image/' . date('Ymd') . "/" . $filename;
            $result = $ossClient->uploadFile($bucket, $filename2, $filePath);

            unlink($filePath);

            if(isset($result['info']['url']) && is_array($result)){
                $data2['image'] = "https://xingjukuaidi.oss-cn-beijing.aliyuncs.com/".$filename2;
                return $this->data($data2);
            }else{
                return  $this->fail('请重新获取');
            }

        } catch (RequestException $e) {
            return $this->fail($e->getMessage());
        }

    }

    /**
     * @return void
     * 升级v1隔天返利到账
     */
    public function profitGive()
    {
        $now = Carbon::now()->timestamp;
        $yesterday = Carbon::now()->subDays(1)->timestamp;
        $profit = MembersProfit::where('type',2)->where('created_at','<',$yesterday)->where('status',0)->get();
        foreach ($profit as $v){
            $userId = $v->user_id;
            $v->status = 1;
            if($v->save()){
                Members::where('id',$userId)->increment('price',$v->profit);
            }
        }

        $orderList = LevelOrders::where('created_at','<',$yesterday)->where('status',1)->get();

        foreach ($orderList as $v){
            if(empty($v))continue;
            $orderSn = $v->order_sn;
            MembersWithdraw::where('out_biz_no',$orderSn)->update(['status'=>1]);
        }

    }


}
